package com.lancoo.klgcourseware.base;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import com.rxjava.rxlife.Scope;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by pengmi on 2019/8/14 11:42
 * Description:
 */
public abstract class BaseKlgPresenter implements Scope, LifecycleEventObserver {

    protected Context mContext;
    private CompositeDisposable mDisposables;

    public BaseKlgPresenter(Context mContext,LifecycleOwner owner) {
        this.mContext = mContext;
        if(owner!=null){
            owner.getLifecycle().addObserver(this);
        }
    }

    public enum LoadStatus{
        REFRESH,LOADMORE
    }


    protected int pageIndex=1;
    protected int pageTotalCount=1;
    protected final int pageSize= 20;
    protected LoadStatus status=LoadStatus.REFRESH;


    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        if (event == Lifecycle.Event.ON_DESTROY) {  //Activity/Fragment 销毁
            source.getLifecycle().removeObserver(this);
            dispose(); //中断RxJava管道
        }
    }

    @Override
    public void onScopeStart(Disposable d) {
        addDisposable(d);
    }

    @Override
    public void onScopeEnd() {

    }

    private void addDisposable(Disposable disposable) {
        CompositeDisposable disposables = mDisposables;
        if (disposables == null) {
            disposables = mDisposables = new CompositeDisposable();
        }
        disposables.add(disposable);
    }

    private void dispose() {
        final CompositeDisposable disposables = mDisposables;
        if (disposables == null) return;
        disposables.dispose();
    }
}
